package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 小坏
 * @Date 2021/1/25 14:33
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 */

@Controller
public class HelloController {


    @Value("${sso.server.url}")
    private String ssoserverurl;

    /**
     * 无需登录就可以访问
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 感知这次是sessionserver登录成功跳回来的
     * <p>
     * 直接访问是没有令牌的
     * 跳转有令牌
     *
     * @param model
     * @param session
     * @param token 只要ssoservewr 登录成功跳回来就会带上
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if(!StringUtils.isEmpty(token)){
            //只要ssoservewr 登录成功跳回来就会带上
            RestTemplate template = new RestTemplate();
            ResponseEntity<String> forEntity = template.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //没有登录跳转登录服务器
            //跳转过去以后，使用url上的查询参数标识我们自己是那个页面
            return "redirect:" + ssoserverurl + "?redirect_url=http://client2.com:8082/boss";

        }
        List<String> list = new ArrayList<>();
        list.add("张三");
        list.add("王五");
        model.addAttribute("emps", list);
        return "list";
    }


}
